#!/usr/bin/python2.5
# -*- coding: utf-8 -*-
# Copyright (c) 2008 Christoph Heer (Christoph.Heer@googlemail.com)
# 
# Permission is hereby granted, free of charge, to any person obtaining a 
# copy of this software and associated documentation files (the \"Software\"), 
# to deal in the Software without restriction, including without limitation 
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the 
# Software is furnished to do so, subject to the following conditions: 
# 
# The above copyright notice and this permission notice shall be included in 
# all copies or substantial portions of the Software. 
# 
# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
# DEALINGS IN THE SOFTWARE. 

#===============================================================================
# A very Simple AntiFlood Application
# by Christoph Heer (Christoph.Heer@gmail.com)
#===============================================================================

#Import von Modulen
import PyTeamspeak2
import time
import pystyle
import yaml
import sys
import os

#Einstellungen Global
global ServerIP
global ServerUDPPort
global TCPQueryPort
global SLoginUsername
global SLoginPassword

#ZusatzFunktionen
def globalban(ip, time):
    sl = Teamspeak.sl()
    for id in sl:
        Teamspeak.sel(id)
        Teamspeak.banadd(ip,time)
    Teamspeak.sel(config['ServerUDPPort'])

#Lade ConfigFile
try:
    global config
    appdir = os.path.dirname(os.path.abspath(__file__))
    configfile = os.path.join(appdir, "config.yaml")
    config = yaml.load(file(configfile, 'r'))
except yaml.YAMLError, exc:
    pystyle.msgerror("Error in configuration file:", exc)
    sys.exit()

# Neue Instanz von TCPQuery aus PyTeamspeak2
global Teamspeak
Teamspeak = PyTeamspeak2.TCPQuery(config['ServerIP'],config['TCPQueryPort'])
TeamspeakLog = PyTeamspeak2.LogParser()
def main():
    pystyle.msgheader('TSnake-Antiflooder by Christoph Heer (Christoph.Heer@gmail.com)')
    #Verbinde zum Server
    pystyle.msgwork('Connect TS-Server')
    msg = Teamspeak.xconnect()
    if msg[0] == 'ERROR':
        pystyle.msgerror(msg[2])
        sys.exit()
    else:
        pystyle.msgok('LINK ONLINE')
    #Auswaehlen vom TSServer
    msg = Teamspeak.sel(config['ServerUDPPort'])
    if msg[0] == 'ERROR':
        pystyle.msgerror(msg[2])
        sys.exit()
    else:
        pystyle.msgok('MAIN Server selected')
    #Login als Superadmin
    pystyle.msgwork('Send Login Data')
    msg = Teamspeak.slogin(config['SLoginUsername'],config['SLoginPassword'])
    if msg[0] == 'ERROR':
        pystyle.msgerror(msg[2])
        sys.exit()
    else:
        pystyle.msgok('Login OK')
    #Sende Online Message
    pystyle.msgwork('Send TS Message')
    msg = Teamspeak.msgall('[TSnake][ANTI-FLOOD] Now Online and Ready!!!')
    if msg[0] == 'ERROR':
        pystyle.msgerror(msg[2])
        sys.exit()
    else:
        pystyle.msgok('Message was sendet')
        
    #Speicher
    spammerip = []
    spammmsg = []
    resetstarttime = time.clock()
    resetintervall = 10
    pystyle.msgwork('Start AntiFlood')
    #Starte Schleife
    while True:
        #Lade Log
        log = Teamspeak.log(7)
        #Parse Log
        log = TeamspeakLog.parse(log)
        #Pruefe Log
        for line in log:
            if line[4] == 'AccessLog' and line[6] == 'client connected':
                #Wenn IP mehr als 3mal im Speicher exestiert => BAN
                if spammerip.count(line[7]) >= 3:
                    globalban(line[7], 10)
                    Teamspeak.msgall('[TSnake][ANTI-FLOOD] The IP %s is a SPAMMER!!' % (line[7]))
                    Teamspeak.logmark('[TSnake][ANTI-FLOOD] The IP %s is a SPAMMER!!' % (line[7]))
                else:
                    #Fuege IP Speicher hinzu
                    spammerip.append(line[7])
                                
        spammerip = []
        time.sleep(0.2)

if __name__ == "__main__":
    main()